/* 
用户相关数据仓库
state,
mutations,
actions,
getters
*/
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from "@/api/user";
import { constantRoutes, resetRouter } from '@/router'
const state = {
  token: getToken(),//从缓存中获取token
  userInfo: {},
  routes: []
}
const mutations = {
  //存储token
  setToken(state, token) {
    //state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  //存储用户信息
  setUserInfo(state, data) {
    state.userInfo = data
  },
  //存储静态路由+动态路由
  setRoutes(state, routes) {
    state.routes = [...constantRoutes, ...routes]
  }
}
const actions = {
  //用户登录请求
  async login(context, data) {
    const token = await login(data)
    context.commit('setToken', token)
  },
  //请求用户数据
  async getUserInfo(context) {
    const result = await getUserInfo()
    context.commit('setUserInfo', result)
    return result
    /* 将获取到的用户数据返回出去 */
  },
  //用户退出请求
  async logout(context) {
    //清除用户数据
    context.commit('setUserInfo', {})
    //清除token
    context.commit('removeToken')
    //重置路由
    resetRouter()
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}